package com.gvsoft.communication.net.adapter;

import com.gvsoft.communication.net.IoBuffer;
import com.gvsoft.communication.net.NSocket;
import com.gvsoft.communication.net.model.IOrder;
import sun.misc.BASE64Decoder;

import java.nio.ByteBuffer;

/**
 * Created with IntelliJ IDEA.
 * ProjectName:MService
 * Author: zhaoqiubo
 * Date: 15/11/25
 * Time: 上午10:33
 * Desc: 字符串处理适配器
 */
public class StringAdapter implements IOAdapter {
    //定义包头的字节大小
    public final static int PACKET_HEAD_LENGTH = 4;


    @Override
    public void analyWrite(IOrder iOrder, ByteBuffer byteBuffer) {
        byteBuffer.clear();
        String str = encode(iOrder.generateOrderStr());
        //得出整个包体的长度
        int packetSize = str.getBytes().length;
        //将包体长度放入buffer的前四位
        byteBuffer.putInt(packetSize);
        //移动buffer的postion指针到第四位，包体将从第四位开始写入
        byteBuffer.position(PACKET_HEAD_LENGTH);
        //写入包体
        byteBuffer.put(str.getBytes());
        byteBuffer.flip();
    }

    @Override
    public void onError(NSocket nSocket, Throwable t) {

    }

    @Override
    public String encode(String s) {
        if (s == null) {
            return null;
        }
        return (new sun.misc.BASE64Encoder()).encode(s.getBytes());
    }

    @Override
    public String decode(String s) {
        if (s == null) {return null;}
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            byte[] b = decoder.decodeBuffer(s);
            return new String(b);
        } catch (Exception e) {
            return null;
        }
    }
    @Override
    public Object analyRead(IoBuffer buf) {
        if (buf.remaining() < PACKET_HEAD_LENGTH) return null;
        buf.mark();
        int len = buf.readInt();
        if (buf.remaining() < len) {
            buf.reset();
            return null;
        }
        byte[] b = new byte[len];
        buf.readBytes(b);
        return new String(b);

    }
}
